<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 订单
 *
 * @author      Eden
 * @datetime    2016/12/1 20:28
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Lists_Model extends API_Model
{

    /**
     * 每页条数
     */
    const PAGE_SIZE = 20;

    private $params = array();

    private $width = 320;
    private $height = 180;

    private $orderStatus = array(
        'Unpaid','Pending','Dispatch','Complete', 'Refund'
    );

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run(Array $params)
    {
        $this->params = $params;
        $send['state'] = false;
        do {
            // 检查参数
            if (!$this->_checkParams()) {
                $send['error'] = $this->getError();
                break;
            }

            $res = $this->getLists();
            $send['state'] = true;
            $send['data'] = $res;

        } while(false);
        $this->output->send($send);
    }

    public function getLists()
    {
        $page = 1;
        if (isset($this->params['page'])) {
            $page = intval($this->params['page']);
            $page = $page <= 0 ? 1 : $page;
        }

        $offset = ($page - 1) * self::PAGE_SIZE;

        $where = array();
        $where['userId'] = $this->params['userId'];
        $where['status'] = $this->params['orderStatus'];

        if ($this->params['orderStatus'] == 'Complete') {
            $where['commented'] = 0;
        }

        $countDb = clone($this->db);
        $countDb->where($where);
        $counts = $countDb->count_all_results('user_order');

        if ($counts == 0) {
            return array(
                'total' => 0,
                'nextPage' => false,
                'data' => array()
            );
        }

        $query = $this->db->select()
            ->from('user_order')
            ->limit(self::PAGE_SIZE, $offset)
            ->where($where)
            ->get();

        $orders = $query->result_array();

        return array(
            'total' => $counts,
            'nextPage' => $counts > ($page * self::PAGE_SIZE),
            'data' => $this->_searchGoods($orders)
        );

    }

    private function _searchGoods($orders)
    {
        $orderIds = array();
        if (!empty($orders) && is_array($orders)) foreach ($orders as $order) {
            array_push($orderIds, $order['id']);
        }

        $goodsDb = clone($this->db);
        $query = $goodsDb->select('uog.num, uog.price, uog.orderId, uog.goodsId, sg.goodsName, sg.baseId, sg.streamId, sg.thumb, sg.bannerThumb, sg.liveUrl, sg.expressWeight, sg.status')
            ->where_in('uog.orderId', $orderIds)
            ->from('user_order_goods as uog')
            ->join('base_goods as sg', 'sg.id = uog.goodsId')
            ->get();
        $results = $query->result_array();
        $ordersGoods = array();
        if ($results) foreach ($results as $item) {
            $orderId = $item['orderId'];
            if (empty($ordersGoods[$orderId])) {
                $ordersGoods[$orderId] = array();
            }

            $thumb = !empty($item['bannerThumb']) ? $item['bannerThumb'] : $item['thumb'];
            $goodsItem = array(
                'goodsId' => (int) value($item, 'goodsId'),
                'goodsName' => value($item, 'goodsName'),
                'num' => (int) value($item, 'num'),
                'price' => doubleval(money_format('%i', $item['price'])),
                'baseId' => intval($item['baseId']),
                'thumb' => thumb($thumb, $this->width, $this->height),
                'expressWeight' => doubleval($item['expressWeight']),
                'status' => $item['status'] == 1 ? 'onSale' : 'offSale',
                'isLive' => !empty($item['liveUrl']),
                'liveUrl' => value($item, 'liveUrl', '')
            );
            $ordersGoods[$orderId][] = $goodsItem;
        }

        $ret = array();
        foreach($orders as $goods) {
            $orderId = $goods['id'];
            $returns = array();
            $returns['orderId'] = (int) $goods['id'];
            $returns['sn'] = value($goods, 'sn');
            $returns['totalPrice'] = doubleval($goods['totalPrice']);
            $returns['goodsPrice'] = doubleval($goods['goodsPrice']);
            $returns['expressPrice'] = doubleval($goods['expressPrice']);
            $returns['voucher'] = $goods['voucher'];
            $returns['addressId'] = (int) value($goods, 'addressId');
            $returns['payMode'] = value($goods, 'payMode', 'online');
            $returns['created'] = value($goods, 'created');
            $returns['status'] = value($goods, 'status');
            $returns['message'] = value($goods, 'message', '');
            $returns['goods'] = $ordersGoods[$orderId];
            $ret[] = $returns;
        }

        return $ret;
    }

    /**
     * 检查参数
     * @return bool
     */
    private function _checkParams()
    {
        if (empty($this->params['userId']) || empty($this->params['orderStatus'])) {
            $this->setError('参数错误');
            return false;
        }

        $orderStatus = value($this->params, 'orderStatus');
        $orderStatus = strtolower($orderStatus);
        $orderStatus = ucfirst($orderStatus);
        if (!in_array($orderStatus, $this->orderStatus)) {
            $this->setError('无效订单状态');
            return false;
        }

        return true;
    }
}
